import { createWebHistory, createRouter } from "vue-router";

// 公共路由
export const constantRoutes = [
  //   {
  //     path: "/",
  //     component: () => import("@/views/layout/Layout.vue"),
  //     hidden: true,
  //   },
  {
    path: "/login",
    component: () => import("@/views/Login.vue"),
    hidden: true,
  },
  {
    path: "/register",
    component: () => import("@/views/Register.vue"),
    hidden: true,
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
});

// 动态路由，根据浏览器中保存的用户权限动态生成
export const setDynamicRoutes = () => {
  const storeMenus = localStorage.getItem("menus");
  // 确定有权限菜单，就把根路径"/"定向到首页
  if (storeMenus) {
    const manageRoute = {
      path: "/",
      name: "首页",
      component: () => import("@/views/layout/Layout.vue"),
      //   redirect: "/worker/login", // 应该去掉，在已经登录的情况下，不需要重定向到登录页
      children: [],
    };
    const menus = JSON.parse(storeMenus);
    menus.forEach((item) => {
      // path不为空代表自身为一级菜单，需要添加路由
      if (item.pagePath) {
        manageRoute.children.push({
          path: item.pagePath,
          name: item.menuName,
          component: () =>
            import(/* @vite-ignore */ `/src/views${item.pagePath}.vue`),
        });
      } else if (item.children) {
        // path为空代表没有对应页面，不需要添加路由，只需要添加二级子菜单
        item.children.forEach((child) => {
          manageRoute.children.push({
            path: child.pagePath,
            name: item.menuName + "/" + child.menuName,
            component: () =>
              import(/* @vite-ignore */ `/src/views${child.pagePath}.vue`),
          });
        });
      }
    });

    //
    const currentRouteNames = router.getRoutes().map((v) => v.name);
    if (!currentRouteNames.includes("首页")) {
      router.addRoute(manageRoute);
    }
  }
};

// 刷新页面时，重新生成动态路由（防止刷新后动态路由丢失导致白屏）
setDynamicRoutes();

export default router;
